(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:mynewarea
     * @description

     用法：
     <mynewarea ng-model="item.cid" dft="1"></mynewarea>
     注：必须绑定ng-model;dft=1代表自动选中最后一个节点

     * # myarea
     */
    angular.module('webApp')
        .directive('mynewarea', function() {
            return {
                restrict: 'E',
                template: '<span><i class="sui-icon icon-tb-cascades"></i> <a href="javascript:;"></a></span>',
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    disabledcitys: "=",
                },
                controller: ['$templateCache', '$scope', 'dataService', '$compile', '$timeout', function($templateCache, $scope, dataService, $compile, $timeout) {
                    var zTreeObj;
                    $scope.b = [];

                    $scope.ngModel = $scope.ngModel || [];
                    $scope.disabledcitys = $scope.disabledcitys || [];

                    //初始化所有城市数据
                    $scope.zNodes1 = [];
                    $scope.zNodes = [];
                    dataService.getProvinceCity(function(result) {
                        //原始数据
                        $scope.zNodes = result;
                    });

                    $scope.initNodes = function() {
                        $scope.zNodes1 = clone($scope.zNodes);
                        _.map($scope.zNodes1, function(treeNode) {
                            _.map(treeNode.children, function(area) {
                                if ($scope.ngModel.indexOf(String(area.id)) != -1) {
                                    area.checked = true;
                                }
                                if ($scope.disabledcitys.indexOf(String(area.id)) != -1) {
                                    // 有禁止城市的父级不允许有选择框
                                    treeNode.nocheck = "true";

                                    area.checked = true;
                                    area.chkDisabled = true;
                                }
                            });
                        });
                    }

                    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
                    var setting = {
                        check: {
                            enable: true,
                            chkStyle: "checkbox",
                            chkboxType: {
                                "Y": "ps",
                                "N": "ps"
                            },
                            nocheckInherit: false,
                            autoCheckTrigger: true
                        },
                        callback: {
                            onClick: function(event, treeId, treeNode, clickFlag) {
                                zTreeObj.checkNode(treeNode, true, true, true);
                            },
                            onCheck: function(event, treeId, treeNode) {
                                if (treeNode.checked) {
                                    $scope.b.push(String(treeNode.id));
                                } else {
                                    $scope.b.splice($scope.b.indexOf(String(treeNode.id)), 1);
                                }
                            },
                        },
                        data: {
                            simpleData: {
                                enable: true
                            }
                        }
                    };

                    $scope.showPop = function() {
                        $scope.initNodes();
                        $scope.b = clone($scope.ngModel);
                        $timeout(function() {
                            $.alert({
                                backdrop: 'static',
                                keyboard: true,
                                title: '{{"choice" | translate}}',
                                body: '<div><div style="height:365px;overflow-y: scroll;"><ul id="catTreearea" class="ztree" ></ul></div><div ng-show="fjvalue.name" style="margin-top: 10px;">{{"area" | translate}}：{{checkedv}}</div></div>',
                                okBtn: '{{"ok" | translate}}',
                                closeBtn: true,
                                transition: true,
                                height: "400px",
                                show: function(e) {
                                    zTreeObj = $.fn.zTree.init($("#catTreearea"), setting, $scope.zNodes1);
                                    zTreeObj.expandAll(false);
                                    $compile($(e.currentTarget).contents())($scope);
                                    return true;
                                },
                                okHide: function(e) {
                                    $timeout(function() {
                                        $scope.ngModel = $scope.unique($scope.b);
                                    });
                                },
                            });
                        })
                    }

                    $scope.unique = function(array) {
                        var r = [];
                        for (var i = 0, l = array.length; i < l; i++) {
                            for (var j = i + 1; j < l; j++)
                                if (array[i] === array[j]) j = ++i;
                            r.push(array[i]);
                        }
                        return r;
                    }
                }],
                link: function(scope, element, attrs, ctrl) {
                    //处理数据，得到想要 的数据
                    //绑定点击事件
                    element.bind("click", function() {
                        scope.showPop();
                    });
                    element.addClass("address");
                }
            }
        })
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.choseprovince.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('choseProvince', function() {
            return {
                restrict: 'E',
                template: '<label data-toggle="checkbox" class="checkbox-pretty inline"><input type="checkbox" name="checkbox" ng-click="isChecked($event)"><span>包邮</span></label> <span ng-show="setStatus"> <button class="sui-btn btn-link" ng-click="setProvince()">设置包邮地址</button><span style="color:#ccc">默认全国包邮</span></span>',
                require: 'ngModel',
                scope: {
                    ngModel: '='
                },
                controller: ['$templateCache', '$scope', 'dataService', '$compile', '$timeout', '$rootScope', function($templateCache, $scope, dataService, $compile, $timeout, $rootScope) {
                    $scope.ngModel = $scope.ngModel || [];

                    $rootScope.$on('event:chose-province', function(event, data) {
                        $scope.ngModel = data.city;
                        if ($scope.ngModel != 1) {
                            $scope.chosedProvince1 = $scope.ngModel;
                        }

                        if ($scope.ngModel && JSON.stringify($scope.ngModel) != "[]") {
                            $("input[name='checkbox']").parent().addClass('checked');
                            $("input[name='checkbox']").attr("checked", true);
                            $scope.setStatus = true;
                        }
                    });

                    //选中包邮 出现 设置包邮地区，默认全国包邮
                    $scope.isChecked = function($event) {
                        var status = $event.currentTarget.checked;
                        if (status) {
                            $scope.setStatus = true;
                            $scope.ngModel = 1;
                        } else {
                            $scope.setStatus = false;
                            $scope.ngModel = [];
                        }
                    }

                    //设置省份
                    $scope.setProvince = function() {
                        $scope.getAllProvince().then($scope.showPop)
                    }

                    //查询省份
                    $scope.getAllProvince = function() {
                        $scope.provinces = [];
                        return dataService.areaGet({
                            query: {
                                parent_id: 0
                            },
                            page_size: 34
                        }).then(function(provinces) {
                            if (provinces.total_count) {
                                _.map(provinces.areas, function(area) {
                                    if ($scope.ngModel != 1 && $scope.ngModel.indexOf(area.area_id) > -1) {
                                        area.checked = true;
                                    } else {
                                        area.checked = false;
                                    }
                                    $scope.provinces.push(area);
                                });
                            }
                        });
                    }

                    $scope.showPop = function() {
                        $timeout(function() {
                            $.alert({
                                backdrop: 'static',
                                keyboard: true,
                                title: '{{"choice" | translate}}',
                                body: $templateCache.get("views/directives.choseprovince.html"),
                                okBtn: '{{"ok" | translate}}',
                                closeBtn: true,
                                transition: true,
                                height: "350px",
                                show: function(e) {
                                    $compile($(e.currentTarget).contents())($scope);
                                    return true;
                                },
                                okHide: function(e) {
                                    $timeout(function() {
                                        if ($scope.chosedProvince && $scope.chosedProvince.length) {
                                            $scope.ngModel = $scope.chosedProvince;
                                            // console.error("ngModel", $scope.ngModel);
                                        } else {
                                            $scope.ngModel = 1;
                                        }
                                    });
                                },
                            });
                        })
                    }

                    //全选
                    $scope.selectAll = function() {
                        $("input[name='province']").parent().addClass('checked');
                        $("input[name='province']").attr("checked", true);

                        $scope.chosedProvince = [];
                        $("input[name='province']:checked").each(function() {
                            $scope.chosedProvince.push($(this).val());
                        });
                    }

                    //取消
                    $scope.cancleAll = function() {
                        $("input[name='province']").parent().removeClass('checked');
                        $("input[name='province']").attr("checked", false);

                        $scope.chosedProvince = [];
                    }

                    //单个选中
                    $scope.chosedProvince1 = [];
                    $scope.selectOne = function($event, area_id) {
                        var status = $event.currentTarget.checked;
                        if (status) {
                            $scope.chosedProvince1.push(area_id);
                        } else {
                            var index = $scope.chosedProvince1.indexOf(area_id);
                            $scope.chosedProvince1.splice(index, 1);
                        }
                        // console.error("chosedProvince1", $scope.chosedProvince1);
                        $scope.chosedProvince = $scope.chosedProvince1;
                    }
                }],
                link: function(scope, element, attrs, ctrl) {}
            }
        });
})();